<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\Relation;
use app\common\tool\Result;
use think\facade\View;
use think\Response;
use think\response\Json;
use addons\Builder\facade\Builder;
use app\common\model\Assets;
use app\common\model\Level;
use app\common\model\Logs;
use think\exception\ValidateException;

class User extends Base
{
    protected string $pk = 'id';

    protected string $validate = 'User';

    protected string $model = '\app\common\model\User';

    protected array $hasOne = ['level', 'assets'];

    protected array $sort = [
        'ordinary' => [
            'create_time' => 'desc'
        ],
        'formal'   => [
            'active_time' => 'desc'
        ]
    ];

    public function ordinary(): string
    {
        return $this->fetch(['delete'], ['add' => ['size' => '50%']], ['is_active', '=', 1]);
    }

    public function formal(): string
    {
        return $this->fetch([], [], ['is_active', '=', 2]);
    }

    public function fetch($rb = [], $tb = [], $extra_map = []): string
    {

        return Builder::Table()
            ->autoStructure($this->model, $this->pk, 'barDemo,' . ($rb ? '190' : '140'))
            ->autoSpliceColumns(6, Assets::getFields(3), "assets", true)
            ->addRightButtons(
                array_merge([
                    'login' => ['title' => '登录', 'url' => url('user/login')->build()],
                    'edit'  => ['size' => '50%']
                ], $rb))
            ->addTopButtons(
                array_merge($tb, [
                    'reset_1' => [
                        'title'       => '重置登录密码',
                        'placeholder' => '请填写新密码，默认111111',
                        'icon'        => 'layui-icon-password',
                        'url'         => url('user/reset', ['type' => 1])->build(),
                        'event'       => '_batchPrompt'
                    ],
                    'reset_2' => [
                        'title'       => '重置支付密码',
                        'placeholder' => '请填写新密码，默认222222',
                        'icon'        => 'layui-icon-password',
                        'url'         => url('user/reset', ['type' => 2])->build(),
                        'event'       => '_batchPrompt'
                    ],
                    'export'
                ]))
            ->addExtraMap([$extra_map])
            ->addSearch([
                ['code__nickname__mobile', '会员编号/昵称/手机号', 'input,Like']
            ])
            ->addSearchList([
                [
                    'filed' => 'level_id',
                    'title' => '会员等级',
                    'child' => Level::field('id as value,title')->select()
                ],
            ])
            ->fetch();
    }

    public function save($param = [], $model = true): Json
    {
        return parent::save($this->request->post(), $model); // TODO: Change the autogenerated stub
    }

    public static function getLevel(): array
    {
        return array_merge([0 => '暂无'], Level::column('title', 'id'));
    }

    public function reset($type): Response
    {
        try {
            $ids = $this->request->post('ids');
            $pass = $this->request->post('pass');
            if ($type == 1) {
                $key = 'password';
                $value = md5($pass ?: '111111');
                $name = '登录密码';
            } else {
                $key = 'pay_password';
                $value = md5($pass ?: '222222');
                $name = '支付密码';
            }
            $this->model::update([$key => $value], ['id' => $ids]);
            $msg = '重置了【' . $name . '】会员标识ID【' . implode(',', $ids) . '】';
            Logs::adds($msg, $this->admin->id, $this->admin->admin_name);
            return Result::success('已重置');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }
    public function login(): Response
    {
        try {
            $id = $this->request->param('id');
            $user = $this->model::find($id);
            if ($user->token) {
                $token = $user->token;
            } else {
                $token = md5(time() . json_encode($user));
                $user->token = $token;
                $user->save();
            }
            cookie('token', $token);
            $description = '登录操作，会员【' . $user->code . '】';
            Logs::adds($description, $this->admin['id'], $this->admin['admin_name']);
            return Result::fastReturn(['code' => 1, 'msg' => '登录成功', 'data' => ['code' => $user->code, 'url' => '/']]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    public function recharge(): Response|string
    {
        $param = $this->request->param();
        if ($this->request->isAjax()) {
            switch ($param['type']) {
                case "get":
                    $user = $this->model::whereLike('code|mobile|nickname', '%' . $param['val'] . '%')
                        ->field('id,code,mobile,nickname')->select();
                    return Result::success('success', $user, 0);
                case "account":
                    $assets = Assets::where('uid', $param['id'])->value($param['val']);
                    if ($assets) {
                        return Result::fastReturn(['code' => 1, 'msg' => '', 'result' => $assets]);
                    } else {
                        return Result::fail('加载失败');
                    }
                case "save":
                    try {
                        $this->validate($param, 'Recharge');
                    } catch (ValidateException $e) {
                        return Result::fail($e->getError());
                    }
                    return $this->model::recharge($param, $this->admin);
                default:
                    return Result::fail('加载失败');
            }
        }
        View::assign('assets', Assets::getFields(3));
        return View::fetch();
    }

    public function delete(): Response
    {
        try {
            $user = $this->model::where('id', $this->request->post($this->pk))->find();
            if (empty($user)) {
                return Result::fail('会员不存在');
            }
            if ($user->is_active == 2) {
                return Result::fail('会员已激活，无法删除');
            }
            $count = Relation::where('uid', $user->id)->count();
            if ($count) {
                return Result::fail('该会员已推荐会员无法删除');
            }
            Relation::destroy(['new_uid' => $user->id], true);
            $this->model::destroy(['id' => $user->id], true);

            Logs::adds('删除会员【' . $user->code . '】', $this->admin->id, $this->admin->admin_name);
            return Result::success('已删除');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }

}
